package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sky.constant.MessageConstant;
import com.sky.context.BaseContext;
import com.sky.dto.*;
import com.sky.entity.*;
import com.sky.exception.AddressBookBusinessException;
import com.sky.exception.ShoppingCartBusinessException;
import com.sky.mapper.AddressBookMapper;
import com.sky.mapper.OrderDetailMapper;
import com.sky.mapper.OrderMapper;
import com.sky.mapper.ShoppingCartMapper;
import com.sky.result.PageResult;
import com.sky.service.OrderService;
import com.sky.utils.WeChatPayUtil;
import com.sky.vo.OrderPaymentVO;
import com.sky.vo.OrderStatisticsVO;
import com.sky.vo.OrderSubmitVO;
import com.sky.vo.OrderVO;
import com.sky.websocket.WebSocketServer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.*;

/**
 * @Author
 * @Date 2024/5/16 18:49
 * @Description:
 */
@Service
@Slf4j
public class OrderServiceImpl  extends ServiceImpl<OrderMapper, Orders> implements OrderService {
    @Autowired
    private AddressBookMapper  addressBookMapper;
    @Autowired
    private ShoppingCartMapper shoppingCartMapper;
    @Autowired
    private OrderDetailMapper  orderDetailMapper;
    @Autowired
    private WeChatPayUtil weChatPayUtil;
    @Autowired
    private WebSocketServer webSocketServer;
    @Override
    public OrderSubmitVO submit(OrdersSubmitDTO ordersSubmitDTO) {
        //判断地址和购物车是否为空
        //获取地址
        AddressBook addressBook=addressBookMapper.selectById(ordersSubmitDTO.getAddressBookId());
        if(addressBook==null){
            throw  new AddressBookBusinessException(MessageConstant.ADDRESS_BOOK_IS_NULL);
        }
        //获取购物车
        List<ShoppingCart> shoppingCarts =shoppingCartMapper.selectList(new QueryWrapper<ShoppingCart>().eq("user_id", BaseContext.getCurrentId()));
        if (shoppingCarts==null||shoppingCarts.size()==0){
            throw  new ShoppingCartBusinessException(MessageConstant.SHOPPING_CART_IS_NULL);
        }

        //提交订单
        Orders orders=new Orders();
        BeanUtils.copyProperties(ordersSubmitDTO,orders);
        orders.setAddress(addressBook.getProvinceName()+addressBook.getDistrictName()+addressBook.getDetail());
        orders.setNumber(String.valueOf(System.currentTimeMillis()));
        orders.setUserId(BaseContext.getCurrentId());
        orders.setStatus(Orders.PENDING_PAYMENT);
        orders.setOrderTime(LocalDateTime.now());
        orders.setPayStatus(Orders.UN_PAID);
        orders.setPhone(addressBook.getPhone());
        orders.setConsignee(addressBook.getConsignee());
        orders.setPackAmount(shoppingCarts.size()*2);
        baseMapper.insert(orders);

        //将购物车数据插入到订单的明细表
        List<OrderDetail> details=new ArrayList<>();
        shoppingCarts.forEach(shoppingCart -> {
            OrderDetail orderDetail=new OrderDetail();
            BeanUtils.copyProperties(shoppingCart,orderDetail);
            orderDetail.setOrderId(orders.getId());
            details.add(orderDetail);
        });
        orderDetailMapper.insertBatch(details);
        //清空当前用户的购物车
        shoppingCartMapper.delete(new QueryWrapper<ShoppingCart>().eq("user_id",BaseContext.getCurrentId()));
        //封装返回结果
        OrderSubmitVO orderSubmitVO=OrderSubmitVO
                .builder()
                .id(orders.getId())
                .orderNumber(orders.getNumber())
                .orderAmount(orders.getAmount())
                .orderTime(orders.getOrderTime())
                .build();


        return orderSubmitVO;
    }
    /**
     * 订单支付
     *
     * @param ordersPaymentDTO
     * @return
     */
    /**

     * 订单支付

     *

     * @param ordersPaymentDTO

     * @return

     */

    public OrderPaymentVO payment(OrdersPaymentDTO ordersPaymentDTO) throws Exception {
        // 当前登录用户id
//        Long userId = BaseContext.getCurrentId();
//        User user = userMapper.getById(userId);

        //调用微信支付接口，生成预支付交易单

//    JSONObject jsonObject = weChatPayUtil.pay(

//        ordersPaymentDTO.getOrderNumber(), //商户订单号

//        new BigDecimal(0.01), //支付金额，单位 元

//        "苍穹外卖订单", //商品描述

//        user.getOpenid() //微信用户的openid

//    );

//    if (jsonObject.getString("code") != null && jsonObject.getString("code").equals("ORDERPAID")) {

//  throw new OrderBusinessException("该订单已支付");

//    }
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("code", "ORDERPAID");

        OrderPaymentVO vo = jsonObject.toJavaObject(OrderPaymentVO.class);
        vo.setPackageStr(jsonObject.getString("package"));
        //为替代微信支付成功后的数据库订单状态更新，多定义一个方法进行修改
        Orders orders=Orders.builder()
                            .number(ordersPaymentDTO.getOrderNumber())
                            .payStatus(Orders.PAID)
                            .status(Orders.TO_BE_CONFIRMED)
                            .checkoutTime(LocalDateTime.now())
                            .build();

        lambdaUpdate().eq(Orders::getNumber,ordersPaymentDTO.getOrderNumber())
                .update(orders);


        // 下单成功返回用户下单信息
        Map map=new HashMap();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号为"+orders.getNumber());

        String json= JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
        return vo;

    }

    /**
     * 支付成功，修改订单状态
     *
     * @param outTradeNo
     */
    public void paySuccess(String outTradeNo) {

        // 根据订单号查询订单
        Orders ordersDB = baseMapper.selectOne(new QueryWrapper<Orders>().eq("number", outTradeNo));

        // 根据订单id更新订单的状态、支付方式、支付状态、结账时间
        Orders orders = Orders.builder()
                .id(ordersDB.getId())
                .status(Orders.TO_BE_CONFIRMED)
                .payStatus(Orders.PAID)
                .checkoutTime(LocalDateTime.now())
                .build();

        baseMapper.updateById(orders);
    }
    /**
     * 订单分页查询 服务端
     *
     * @param
     * @param ordersPageQueryDTO
     */
    @Override
    public PageResult getOrderList(OrdersPageQueryDTO ordersPageQueryDTO) {
        //添加分页查询条件
        Page <Orders> page=new Page<>(ordersPageQueryDTO.getPage(),ordersPageQueryDTO.getPageSize());
        page.addOrder(new OrderItem("order_time",false));

        //查询订单列表,获取查询条件
        String number = ordersPageQueryDTO.getNumber();
        String phone  = ordersPageQueryDTO.getPhone();
        LocalDateTime startTime = ordersPageQueryDTO.getBeginTime();
        LocalDateTime endTime = ordersPageQueryDTO.getEndTime();
        Integer status = ordersPageQueryDTO.getStatus();
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        //根据传入条件进行查询
        queryWrapper.isNotNull(Orders::getNumber)
                .eq(StringUtils.isNotBlank(number), Orders::getNumber, number)
                .eq(StringUtils.isNotBlank(phone), Orders::getPhone, phone)
                .eq(status != null, Orders::getStatus, status)
                .between(startTime != null && endTime != null, Orders::getOrderTime, startTime, endTime);
        Page <Orders> pageResult = page(page, queryWrapper);
        return new PageResult(pageResult.getTotal(),pageResult.getRecords());
    }

    @Override
    public OrderStatisticsVO getClassCount() {
        List<Integer> statusList = new ArrayList<>();
        List<Integer> targetedStatuses = Arrays.asList(2, 3, 4);
        LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
        targetedStatuses.forEach(status -> {
            queryWrapper.in(Orders::getStatus, status);
            statusList.add(Math.toIntExact(baseMapper.selectCount(queryWrapper)));
        });
        OrderStatisticsVO orderStatisticsVO=OrderStatisticsVO.builder()
                .toBeConfirmed(statusList.get(0))
                .confirmed(statusList.get(1))
                .deliveryInProgress(statusList.get(2))
                .build();
        return orderStatisticsVO;
    }

    @Override
    public void update(OrdersRejectionDTO ordersRejectionDTO) {
        lambdaUpdate().eq(Orders::getId,ordersRejectionDTO.getId())
                .set(Orders::getStatus,Orders.CANCELLED)
                .set(Orders::getRejectionReason,ordersRejectionDTO.getRejectionReason())
                .update();
    }

    @Override
    public void confirm(OrdersConfirmDTO ordersConfirmDTO) {
        lambdaUpdate().eq(Orders::getId,ordersConfirmDTO.getId())
                .set(Orders::getStatus,Orders.CONFIRMED)
                .update();
    }

    @Override
    public OrderVO getOrderDetails(Long id) {
        //获取订单基本信息
        Orders orders =getById(id);
        OrderVO orderVO = new OrderVO();
        BeanUtils.copyProperties(orders,orderVO);
        //获取订单详细信息
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, id));
        orderVO.setOrderDetailList(orderDetailList);
        return orderVO;
    }

    @Override
    public void delivery(Long id) {
        lambdaUpdate().eq(Orders::getId,id)
                .set(Orders::getStatus,Orders.DELIVERY_IN_PROGRESS)
                .update();
    }

    @Override
    public void complete(Long id) {
        lambdaUpdate().eq(Orders::getId,id)
                .set(Orders::getStatus,Orders.COMPLETED)
                .update();
    }

    @Override
    public void cancel(OrdersCancelDTO ordersCancelDTO) {
        lambdaUpdate().eq(Orders::getId,ordersCancelDTO.getId())
                .set(Orders::getStatus,Orders.CANCELLED)
                .set(Orders::getCancelReason,ordersCancelDTO.getCancelReason())
                .update();
    }

    @Override
    public void reminder(Long id) {
        //用户催单
        Orders orders=baseMapper.selectById(id);
        Map map=new HashMap();
        map.put("type",1);
        map.put("orderId",orders.getId());
        map.put("content","订单号为"+orders.getNumber());

        String json= JSON.toJSONString(map);
        webSocketServer.sendToAllClient(json);
    }

    @Override
    public PageResult getHistoryOrders(Long pagee, Long pageSize, Long status) {
        Page <Orders> page=new Page<>(pagee,pageSize);
        page.addOrder(new OrderItem("order_time",false));

        //查询订单列表,获取查询条件
        LambdaQueryWrapper<Orders> queryWrapper=new LambdaQueryWrapper<>();
        //根据传入条件进行查询

        if(status!=null){
            queryWrapper.eq(Orders::getStatus,status);
        }
        Page <Orders> pageResult = page(page, queryWrapper);

        //获取到查询到的订单数据进行订单详细信息的填充
        List<Orders> records = pageResult.getRecords();
        List<OrderVO> orderVOList=new ArrayList<>();
        records.forEach(orders -> {
            OrderVO orderVO=new OrderVO();
            BeanUtils.copyProperties(orders,orderVO);
            Long id = orders.getId();
            List<OrderDetail> orderDetails=orderDetailMapper.selectList(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId,id));
            orderVO.setOrderDetailList(orderDetails);
            orderVOList.add(orderVO);
        });

        return new PageResult(pageResult.getTotal(),orderVOList);
    }

    @Override
    public void userCancel(Long id) {
        lambdaUpdate().eq(Orders::getId,id)
                .set(Orders::getStatus,Orders.CANCELLED)
                .update();
    }

    @Override
    @Transactional
    public void repetition(Long id) {
        //获取订单明细表数据
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(new LambdaQueryWrapper<OrderDetail>().eq(OrderDetail::getOrderId, id));
        List<ShoppingCart> shoppingCartList=new ArrayList<>();
        //通过明细表获取同样的购物车信息
        orderDetailList.forEach(orderDetail -> {
            ShoppingCart shoppingCart=ShoppingCart.builder()
                    .name(orderDetail.getName())
                    .image(orderDetail.getImage())
                    .userId(BaseContext.getCurrentId())
                    .dishId(orderDetail.getDishId())
                    .setmealId(orderDetail.getSetmealId())
                    .number(orderDetail.getNumber())
                    .amount(orderDetail.getAmount())
                    .createTime(LocalDateTime.now())
                    .build();

            shoppingCartList.add(shoppingCart);
                });
        log.info("购物车数据：{}",shoppingCartList);
        shoppingCartMapper.insertBatch(shoppingCartList);
    }
}
